<template>
  <el-dialog :visible.sync="visible" :close-on-click-modal="false" :title="$tt('label_add_sku')"
    custom-class="dialog_auto">


    <el-form label-width="auto" label-position="right" ref="Form" :model="form" :rules="rules" class="common-form-row">
      <el-row>
        <el-col :span="2">
          <el-form-item :label="$tt('label_select_sku')">
            <sku_selec_input class="w_fill" @changeItem="changeSku" :customerId="customerId" :multiple="false" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="3">
          <el-form-item label-width="0" prop="sku_list">
            <ex_super_table ref="SkuTable" :data="form.sku_list" :model="tableModel" :height="400"
              @selection-change="e => selection = e">
            </ex_super_table>
            <div class="color_danger text_small bold">{{ $tt('tip_create_box_declared_value_and_insured_amount') }}</div>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <span slot="footer" class="dialog_footer">
      <el-button @click="visible = false">{{ $tt('label_cancel') }}</el-button>
      <el-button type="primary" @click="submitBefore">{{ $tt('label_submit') }}</el-button>
    </span>

  </el-dialog>
</template>

<script>
const default_obj = {
  boxNo: "",
  palletNo: "",
  boxLength: "",//	bigdecimal 	箱子长度
  boxWidth: "",//	bigdecimal 	箱子宽度
  boxHeight: "",//	bigdecimal 	箱子高度
  boxWeight: "",//箱子重量
  sku_list: [],
}
import sku_selec_input from '@/component/sku_selec_input'
export default {

  components: { sku_selec_input },
  data() {
    return {


      form: _.cloneDeep(default_obj),
      isPallet: false,
      isInsured: false,

      visible: false,
      TOB: false,
      customerId: null,
      customerName: null,
      customerCode: null,
      selection: [],
      requiredNumberRule: [
        { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        {
          trigger: 'blur',
          validator: (r, v, cb) => {
            if (!this.$reg.PureNumber(v)) {
              return cb(this.$tt("tip_only_positive_pure_decimal"))
            } else if (Number(v <= 0)) {
              return cb(this.$tt("tip_no_less_equal_any", { type: "0" }))
            }
            cb()
          }
        },
      ],

      rules: {

        sku_list: [
          {
            required: true, trigger: 'blur', type: "array", min: 1,
            message: this.$tt('tip_please_add_least_one_sku'),
          }, {
            trigger: 'blur', type: "array",
            validator: (r, v, cb) => {
              const skuGroup = _.groupBy(v, "skuId")
              if (_.values(skuGroup).some(it => it.length > 1)) {
                return cb(this.$tt("tip_some_box_can_no_have_some_sku"))
              }
              cb()
            }
          },
        ]
        // boxLength: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        // boxWidth: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        // boxHeight: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        // boxWeight: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
      },

      tableModel: [
        // { type: 'selection', clickToggle: true, },
        { key: 'skuBarcode', label: 'label_sku_code', width: '140', 'show-overflow-tooltip': true, },
        { key: 'skuName', label: 'label_sku_info', width: '120', 'show-overflow-tooltip': true, },
        {
          key: 'isElectrify', label: 'label_is_electrify', width: '120', 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum")
        },
        {
          key: 'cartonSpec', label: 'label_carton_spec', if: () => this.TOB,
          formatter: (r, c, v) => v ? `${v}/${this.$tt('label_box')}` : this.$t('data_temp_none'),
        },

        {
          key: 'quantity', label: 'label_inbound_box_count', if: () => this.TOB,
          render: (h, { column, row, index }) => {
            const value = row[column.property] / row.cartonSpec

            return (
              <el-form-item
                prop={`sku_list.${index}.quantity`}
                rules={this.requiredNumberRule}
              >
                <el-input-number class='w_fill' value={value} onInput={e => {
                  this.$set(row, column.property, e * row.cartonSpec)
                }}
                  step-strictly min={1} max={999999} />
              </el-form-item>
            )
          }
        },

        {
          key: 'quantity', label: 'label_inbound_count', 'min-width': 120, if: () => !this.TOB,
          render: (h, { column, row, index }) => {

            const value = row[column.property]
            return (
              <el-form-item
                prop={`sku_list.${index}.quantity`}
                rules={this.requiredNumberRule}
              >
                <el-input-number class='w_fill' value={value} onInput={e => this.$set(row, column.property, e)}
                  step-strictly min={1} max={999999} />
              </el-form-item>
            )
          }
        },

        {
          key: 'skuDeclaredAmount', label: 'label_declared_value', 'width': 120, 'show-overflow-tooltip': true,
          formatter: (r, c, v) => this.$formatNameCode(v, r.currencyCode),
        },
        {
          key: 'insuredAmount', label: 'label_single_sku_insurance_amount', 'min-width': 120, if: () => this.isInsured,
          render: (h, { column, row, index }) => {
            if (!this.isInsured) return
            const rule = {
              trigger: 'blur',
              validator: (r, v, cb) => {
                if (this.isInsured) {
                  if (!_.isEmpty(v)) {
                    if (!this.$reg.DigitNumber(v, 2, 9)) {
                      return cb(this.$tt("tip_check_decimal_digit_int", { digit: 2, int: 9 }))
                    } else if (Number(v) > Number(row.skuDeclaredAmount)) {
                      return cb(this.$tt("tip_insured_amount_no_more_declared_amount"))
                    }
                  }
                }
                cb()
              }
            }
            const value = row[column.property]
            return (
              <el-form-item
                prop={`sku_list.${index}.${column.property}`}
                rules={rule}
              >
                <ex_super_input class='w_fill' value={value} onInput={e => this.$set(row, column.property, e)}
                  append={row.currencyCode} />
              </el-form-item>
            )
          },
        },
        {
          type: 'operate', width: 130, operate: [
            {
              label: "label_remove", class: "button_text_danger",
              click: (row, i) => this.form.sku_list.splice(i, 1)
            },
          ]
        }
      ],
    }
  },
  props: {


  },

  computed: {

  },
  methods: {


    changeSku(e) {
      if (!e) return
      const item = _.find(this.form.sku_list, it => it.skuId == e.id)
      if (item) {
        if (this.TOB) return
        item.quantity = item.quantity + 1
        return
      } else {
        if (this.TOB) {
          // if (this.form.sku_list.length >= 1) return this.$message.warning(this.$tt("tip_create_box_tob_no_mix"))
          if (!(e.cartonSpec > 0)) return this.$message.warning(this.$tt("tip_sku_cartonSpec_error_modity_sku_data"))
        }
        let sku = Object.assign({
          skuId: e.id,
          quantity: this.TOB ? e.cartonSpec : 1,
          skuDeclaredAmount: e.skuDeclaredValue,
          insuredAmount: this.isInsured ? e.skuDeclaredValue : 0,
        }, e)
        delete sku.id
        this.form.sku_list.push(sku)
      }

    },
    show({ items, customerId, TOB, isInsured, customerCode }) {
      this.visible = true
      let box_form = _.cloneDeep(default_obj)
      this.TOB = TOB
      box_form.sku_list = items
      this.form = box_form
      this.customerId = customerId
      this.customerCode = customerCode
      this.isInsured = isInsured
    },
    hide() {
      this.visible = false
    },

    submitBefore() {
      if (this.$clickFast()) return
      this.$refs['Form'].validate((valid) => {
        if (valid) {
          this.submit()
        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      });
    },
    submit() {

      let { sku_list, ...other } = this.form

      this.$emit('submitSuccess', {
        list: sku_list.map(it => {
          return {
            isInsurance: this.isInsured && it.insuredAmount ? "Y" : "N",
            ...it,
            ...other,
          }
        })
      }
      )
      this.visible = false
    },
  }
}
</script>
